package cn.byapps.master.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import cn.byapps.master.dao.SysUserMapper;
import cn.byapps.master.entity.SysUser;
import cn.byapps.master.service.UserService;
import cn.byapps.master.vo.ListPageVO;
import cn.byapps.master.vo.UserVO;

@Service
@Transactional
public class UserServiceImpl implements UserService {

	@Autowired
	private SysUserMapper sysUserMapper;

	@Override
	public SysUser getByUser(String username) {
		return sysUserMapper.selectOne(new QueryWrapper<SysUser>().lambda().like(SysUser::getUsername, username));
	}

	@Override
	public ListPageVO getPageVO(Integer page, Integer rows) {
		ListPageVO vo = new ListPageVO();

		vo.setCount(sysUserMapper.selectCount(null));
		List<SysUser> users = sysUserMapper.selectList(null);
		List<UserVO> uservos = new ArrayList<>();
		for (SysUser u : users) {
			UserVO uvo = new UserVO();
			BeanUtils.copyProperties(u, uvo);
			uvo.setRoles(Arrays.asList(u.getRoles().split(",")));
			uservos.add(uvo);
		}
		vo.setUsers(uservos);
		return vo;
	}

	@Override
	public void save(UserVO vo) {
		SysUser sysUser = new SysUser();
		BeanUtils.copyProperties(vo, sysUser);
		sysUser.setRoles(String.join(",", vo.getRoles()));
		sysUserMapper.insert(sysUser);
		
	}

	@Override
	public void update(UserVO vo) {
		SysUser sysUser = sysUserMapper.selectById(vo.getId());
		BeanUtils.copyProperties(vo, sysUser);
		sysUser.setRoles(String.join(",", vo.getRoles()));
		sysUserMapper.updateById(sysUser);
	}

	@Override
	public void delete(UserVO vo) {
		sysUserMapper.deleteById(vo.getId());
	}

}
